import {
    ModalForm,
    ProForm,
    ProFormText,
    ProTable,
} from '@ant-design/pro-components';
import {EditOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, message, Switch} from 'antd';
import React, {useRef} from 'react';
import {page, state, waitTime} from "../../utils/Const";
import {request} from "../../utils/Http";

const User = () => {
    const ref = useRef();
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            width: 80,
        },
        {
            title: 'id',
            dataIndex: 'id',
            valueType: 'string',
            hideInSearch: true,
            hideInTable: true
        },
        {
            title: '账号',
            dataIndex: 'account',
            valueType: 'string',
            editable: false,
        },
        {
            title: '简称',
            dataIndex: 'nickName',
            valueType: 'string',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '手机号',
            dataIndex: 'contactTel',
            valueType: 'string',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '状态(禁用)',
            dataIndex: 'state',
            valueType: 'switch',
            render: (_, record) => {
                return <Switch checked={record.state}
                               onClick={async (checked) => {
                                   const state = checked ? 1 : 0;
                                   await request.put({
                                       url: "sys-user/state/" + record.id + "/" + state,
                                   }).then(res => {
                                       // 刷新并清空,页码也会重置，不包括表单
                                       ref.current?.reload();
                                   }).catch(err => {
                                       // 这里是错误回调
                                       ref.current?.reload();
                                   })
                               }
                               }/>;
            },
            fieldProps: {
                options: state,
            },
            hideInSearch: true,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            editable: false,
        },

        {
            title: '操作',
            width: 120,
            key: 'option',
            valueType: 'option',
            render: (text, record, _, action) => [
                <Button type='link' key="editable" onClick={() => {
                    action?.startEditable?.(record.id);
                }}>
                    设置<EditOutlined/>
                </Button>,
            ],
        },

    ];

    return (
        <ProTable
            className={'data-table'}
            columns={columns}
            rowKey='id'
            actionRef={ref}
            editable={{
                // 单行编辑
                type: 'single',
                // row 有变动的行  originRow 原来的目标行
                onSave: (key, row, originRow) => {
                    row.password = null;
                    delete row.index
                    request.post({
                        url: "sys-user/add-or-edit",
                        params: row
                    }).then(res => {
                        message.success("修改成功");
                        // 刷新并清空,页码也会重置，不包括表单
                        ref.current?.reload();
                    }).catch(err => {
                        // 这里是错误回调
                        console.log(err)
                    })
                },
                onCancel: () => {
                    message.error("您取消了操作");
                },
                onDelete: (key) => {
                    if (key === 1) {
                        message.error('此账号不可以被删除！')
                        // 刷新并清空,页码也会重置，不包括表单
                        ref.current?.reload();
                        return
                    }
                    request.delete({
                        url: "sys-user/del/" + key,
                    }).then(res => {
                        message.success("删除成功");
                        // 刷新并清空,页码也会重置，不包括表单
                        ref.current?.reload();
                    }).catch(err => {
                        // 这里是错误回调
                        console.log(err)
                    })
                }
            }}
            search={{
                labelWidth: 80,
                // 不同的屏幕尺寸的不同适配
                span: {
                    xs: 24,
                    sm: 24,
                    md: 12,
                    lg: 12,
                    xl: 8,
                    xxl: 4,
                }
            }}
            pagination={{
                // showSizeChanger: true,
                responsive: true,
                pageSize: 10
            }}
            request={async (params) => {
                page.pageSize = params.pageSize;
                page.pageCurr = params.current;
                delete params.current
                params = {...page, ...params}
                // 获取数据,注意同步异步的问题
                const data = await request.post({
                    url: "sys-user/page",
                    params: params,
                }).then(res => {
                    return res.data
                }).catch(err => {
                    // 这里是错误回调
                    console.log(err)
                })
                return {
                    total: data.total,
                    success: true,
                    data: data.records,
                };
            }}
            dateFormatter="string"
            headerTitle="系统用户"
            toolBarRender={() => [
                <UserModalForm parentRef={ref}/>
                ,
            ]}

        />
    )
}

/**
 * 对话框
 * @returns {JSX.Element}
 * @constructor
 */
const UserModalForm = (props) => {
    return (<ModalForm
        title="新增系统用户"
        trigger={<Button type="primary">
            <PlusOutlined/>
            新建
        </Button>}
        autoFocusFirstInput
        modalProps={{
            onCancel: () => console.log('run'),
        }}
        submitTimeout={1000}
        width={450}
        onFinish={
            async (values) => {
                await waitTime(1000);
                // 获取数据,注意同步异步的问题
                request.post({
                    url: "sys-user/add-or-edit",
                    params: values,
                }).then(res => {
                    message.success("新增成功");
                    // 刷新并清空,页码也会重置，不包括表单
                    props.parentRef.current.reload();
                }).catch(err => {
                    // 这里是错误回调
                    console.log(err)
                })
                return true;
            }
        }>
        <ProForm.Group>
            <ProFormText name="nickName" label="账号名称" placeholder="名称"
                         rules={[{required: true, message: '账号名称必填!'}]}/>
            <ProFormText name="account" label="登录账号" placeholder="账号"
                         rules={[{required: true, message: '账号必填!'}]}/>
            <ProFormText name="password" label="密码" placeholder="密码"
                         rules={[{required: true, message: '密码必填!'}]}/>
            <ProFormText name="contactTel" label="手机号" placeholder="手机号"/>
        </ProForm.Group>
    </ModalForm>);
};

export default User;